package com.zhe.zheblogmaster.handler.admin;

import com.github.pagehelper.PageInfo;
import com.zhe.zheblogmaster.entity.BlogComment;
import com.zhe.zheblogmaster.service.BlogCommentService;
import com.zhe.zheblogmaster.util.ResultBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.io.Console;

/**
 * @author WHAOU
 * @date 2021/9/17
 * @email whaou@qq.com
 */
@Controller
@ResponseBody
@RequestMapping("/admin/comment")
public class CommentHandler {
    @Autowired
    private BlogCommentService commentService;

    /**
     * 获取当前页的评论列表分页信息
     *
     * @param pageNum 当前页
     * @return 当前页信息，包括评论列表、当前页、总页数、总记录数等
     */
    @GetMapping("/list")
    public ResultBody<PageInfo<BlogComment>> getCommentList(@RequestParam("pageNum") Integer pageNum) {
        PageInfo<BlogComment> pageInfo = commentService.getCommentPage(pageNum);
        return ResultBody.successWithData(pageInfo);
    }

    /**
     * 审核评论记录
     *
     * @param ids 待审核评论id数组
     * @return 审核通过则返回受影响记录数，否则返回错误信息
     */
    @PostMapping("/check")
    public ResultBody<String> check(@RequestBody Integer[] ids) {
        if (ids == null || ids.length < 1) {
            return ResultBody.error("待审核记录id为空，请选择待审核记录");
        }
        int count = commentService.check(ids);
        if (count > 0) {
            return ResultBody.successWithData(String.valueOf(count));
        } else {
            return ResultBody.error("审核失败");
        }
    }

    /**
     * 删除评论记录
     *
     * @param ids 待删除评论id数组
     * @return 删除成功则返回受影响记录数，否则返回错误信息
     */
    @PostMapping("/delete")
    public ResultBody<String> delete(@RequestBody Integer[] ids) {
        if (ids == null || ids.length < 1) {
            return ResultBody.error("待删除评论id数组为空");
        }
        int count = commentService.deleteByIdBatch(ids);
        if (count > 0) {
            return ResultBody.successWithData(String.valueOf(count));
        } else {
            return ResultBody.error("删除失败");
        }
    }

    /**
     * 回复评论
     *
     * @param id    评论id
     * @param reply 回复内容
     * @return 回复成功则返回受影响记录数，否则返回失败原因
     */
    @PostMapping("/reply")
    public ResultBody<String> reply(@RequestParam("commentId") Integer id, @RequestParam("replyBody") String reply) {
        if (id == null || id < 1) {
            return ResultBody.error("参数commentId异常");
        }
        if (!StringUtils.hasLength(reply)) {
            return ResultBody.error("回复内容为空");
        }
        int count = commentService.reply(id, reply);
        if (count > 0) {
            return ResultBody.successWithData(String.valueOf(count));
        } else {
            return ResultBody.error("回复失败");
        }
    }
}
